package com.redis;

import redis.clients.jedis.Jedis;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: sun.hongliang
 * @create: 2018/08/14 17:28
 */
public class RedisLock {

    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WEITH_EXPIRE_TIME = "PX";
    private static final Long RELEASE_SUCCESS = 1L;

    private static Jedis jedis;

    static{
        jedis = new Jedis("47.98.157.6", 6379);
        jedis.auth("Shl@137961");
    }

    public static void main(String[] args) {
        String requestId = UUID.randomUUID().toString();
        String lockKey = "hello";
        boolean lock = tryLock(jedis,lockKey, requestId, 30000);
        System.out.println("lcok:" + lock);
        boolean unLock = unLock(jedis, lockKey, requestId);
        System.out.println("unlock:"+unLock);
    }

    public static boolean tryLock(Jedis jedis,String lockKey,String requestId ,int expiretime){
        String request = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WEITH_EXPIRE_TIME, expiretime);
        if(LOCK_SUCCESS.equals(request)){
            return true;
        }
        return false;
    }

    public static boolean unLock(Jedis jedis, String lockKey, String requestId){
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));

        if (RELEASE_SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }

}
